<template>
  <div class="wechat-bots">
    <!-- 添加/编辑机器人对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '添加微信机器人' : '编辑微信机器人'"
      width="600px"
    >
      <el-form
        ref="formRef"
        :model="botForm"
        :rules="formRules"
        label-width="120px"
      >
        <el-form-item label="机器人名称" prop="name">
          <el-input v-model="botForm.name" placeholder="请输入机器人名称" />
        </el-form-item>
        <el-form-item label="Webhook地址" prop="webhook_url">
          <el-input v-model="botForm.webhook_url" placeholder="请输入Webhook地址" />
        </el-form-item>
        <el-form-item label="密钥" prop="secret_key">
          <el-input v-model="botForm.secret_key" placeholder="请输入密钥（可选）" />
        </el-form-item>
        <el-form-item label="状态" prop="is_active">
          <el-switch v-model="botForm.is_active" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="botForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入描述"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 测试消息对话框 -->
    <el-dialog
      v-model="testDialogVisible"
      title="测试微信机器人"
      width="500px"
    >
      <el-form label-width="100px">
        <el-form-item label="测试消息">
          <el-input
            v-model="testMessage"
            type="textarea"
            :rows="4"
            placeholder="请输入测试消息"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="testDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="sendTestMessage" :loading="testLoading">
            发送测试
          </el-button>
        </span>
      </template>
    </el-dialog>

    <el-card>
      <template #header>
        <div class="card-header">
          <span>微信机器人配置</span>
          <div class="header-actions">
            <el-button type="primary" size="small" @click="showAddDialog">添加机器人</el-button>
            <el-button size="small" @click="loadBots">刷新</el-button>
          </div>
        </div>
      </template>
      
      <el-table :data="bots" style="width: 100%" v-loading="loading">
        <el-table-column prop="name" label="机器人名称" />
        <el-table-column prop="webhook_url" label="Webhook地址" show-overflow-tooltip />
        <el-table-column prop="is_active" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.is_active ? 'success' : 'danger'" size="small">
              {{ row.is_active ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="created_at" label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatTime(row.created_at) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="220" fixed="right">
          <template #default="{ row }">
            <ActionMenu
              :actions="[
                { label: '测试连接', onClick: () => testBot(row) },
                { label: '编辑', onClick: () => editBot(row) },
                { label: row.is_active ? '禁用' : '启用', onClick: () => toggleBot(row) },
                { label: '删除', onClick: () => deleteBot(row) }
              ]"
              :primary-count="2"
            />
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import { systemApi } from '@/api/system'
import type { WechatBotConfig } from '@/types'
import ActionMenu from '@/components/ActionMenu.vue'

const bots = ref<WechatBotConfig[]>([])
const loading = ref(false)
const dialogVisible = ref(false)
const dialogType = ref<'add' | 'edit'>('add')
const formRef = ref<FormInstance>()
const testDialogVisible = ref(false)
const testMessage = ref('')
const testLoading = ref(false)
const currentTestBot = ref<WechatBotConfig | null>(null)

// 表单数据
const botForm = ref<Partial<WechatBotConfig>>({
  name: '',
  webhook_url: '',
  secret_key: '',
  description: '',
  is_active: true
})

// 表单验证规则
const formRules: FormRules = {
  name: [
    { required: true, message: '请输入机器人名称', trigger: 'blur' }
  ],
  webhook_url: [
    { required: true, message: '请输入Webhook地址', trigger: 'blur' },
    { type: 'url', message: '请输入有效的URL地址', trigger: 'blur' }
  ]
}

const loadBots = async () => {
  loading.value = true
  try {
    const response = await systemApi.getWechatBots()
    bots.value = response.data.items
  } catch (error) {
    console.error('Failed to load bots:', error)
    ElMessage.error('加载机器人列表失败')
  } finally {
    loading.value = false
  }
}

const showAddDialog = () => {
  dialogType.value = 'add'
  botForm.value = {
    name: '',
    webhook_url: '',
    secret_key: '',
    description: '',
    is_active: true
  }
  dialogVisible.value = true
}

const editBot = (bot: WechatBotConfig) => {
  dialogType.value = 'edit'
  botForm.value = { ...bot }
  dialogVisible.value = true
}

const submitForm = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    
    if (dialogType.value === 'add') {
      await systemApi.createWechatBot(botForm.value)
      ElMessage.success('添加成功')
    } else {
      await systemApi.updateWechatBot(botForm.value.id!, botForm.value)
      ElMessage.success('更新成功')
    }
    
    dialogVisible.value = false
    loadBots()
  } catch (error) {
    console.error('Form submission failed:', error)
    ElMessage.error('操作失败')
  }
}

const testBot = (bot: WechatBotConfig) => {
  currentTestBot.value = bot
  testMessage.value = `测试消息 - ${new Date().toLocaleString('zh-CN')}`
  testDialogVisible.value = true
}

const sendTestMessage = async () => {
  if (!currentTestBot.value || !testMessage.value.trim()) {
    ElMessage.warning('请输入测试消息')
    return
  }
  
  testLoading.value = true
  try {
    const response = await systemApi.testWechatBot(currentTestBot.value.id, testMessage.value)
    if (response.data.status === 'success') {
      ElMessage.success('测试消息发送成功')
      testDialogVisible.value = false
    } else {
      ElMessage.error('测试消息发送失败')
    }
  } catch (error) {
    console.error('Test bot failed:', error)
    ElMessage.error('测试失败')
  } finally {
    testLoading.value = false
  }
}

const toggleBot = async (bot: WechatBotConfig) => {
  try {
    await systemApi.updateWechatBot(bot.id, { is_active: !bot.is_active })
    ElMessage.success(bot.is_active ? '禁用成功' : '启用成功')
    loadBots()
  } catch (error) {
    console.error('Toggle bot failed:', error)
    ElMessage.error('操作失败')
  }
}

const deleteBot = async (bot: WechatBotConfig) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除机器人 "${bot.name}" 吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await systemApi.deleteWechatBot(bot.id)
    ElMessage.success('删除成功')
    loadBots()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('Delete failed:', error)
      ElMessage.error('删除失败')
    }
  }
}

const formatTime = (time: string): string => {
  if (!time) return '-'
  return new Date(time).toLocaleString('zh-CN')
}

onMounted(() => {
  loadBots()
})
</script>

<style scoped>
.wechat-bots {
  padding: 0;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style> 